<script setup>
import { reactive, ref, getCurrentInstance } from "vue";
import { Toast, ImagePreview } from "vant";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import sendMessage from "@/audios/sendMessage.mp3";
import Emjoi from "@/utils/emjoi";
import { useGetUserInfo } from "@/hooks/chat-hook"

let sendUser = null;

const instance = getCurrentInstance();
const store = useStore();
const user = store.state.user.userInfo;
const route = useRoute();
const router = useRoute();
const notify = store.state.notify;
const nowChats = notify.nowChats;

// 挂载聊天类型
user.type = route.query.type ;

const proxy = instance.appContext.config.globalProperties;

const chatType = route.query.type;
const receiveId = route.query.id;

(async ()=>{
   sendUser = (await useGetUserInfo(receiveId))?.data?.u;
})()

// 聊天类型
Toast(chatType);

const emjoi = Emjoi();
const audio = ref(null);
const s_show = ref(false);
const isEmjoi = ref(false);

const D = reactive({
  message: "",
  autofocus: false,
  emjoi: "",
  msgs: [
  ],
});

let prevAudio = null;
let prevMsg = null;

const showAudio = (e) => {
  let duration;
  const file = e.target.files[0];
  const blob = window.URL.createObjectURL(file);
  const filelement = new Audio(blob);
  filelement.addEventListener("loadedmetadata", function (_event) {
    duration = parseInt(filelement.duration);
    if (duration < 1) {
      return Toast("语音不能小于1秒");
    }
    // 触发私有消息
    proxy.$socket.emit("private message", {
      channel: receiveId,
      msg: blob,
      fromUser:user
    });

    D.msgs.push({
      class: "me",
      blobSrc: blob,
      isAudio: true,
      isPlay: false,
      voiceDuration: duration + " “",
    });
  });
};

const showVideo = (e) => {
  const file = e.target.files[0];
  const blob = window.URL.createObjectURL(file);
  // 触发私有消息
  proxy.$socket.emit("private message", {
    channel: receiveId,
    msg: blob,
    fromUser:user
  });

  D.msgs.push({
    class: "me",
    blobSrc: blob,
    isVideo: true,
  });
};

const showImg = async (e) => {
  const file = e.target.files[0];
  const resource = new Blob([file], {
      type: "image/*",
  })
  const blob = window.URL.createObjectURL(resource);
  // 触发私有消息
  proxy.$socket.emit("private message", {
    channel: receiveId,
    msg: await resource.arrayBuffer(),
    fromUser:user
  });

  D.msgs.push({
    class: "me",
    blobSrc: blob,
    isImg: true,
  });
};

const on_send = (message) => {
  if (D.message.length <= 0) {
    return Toast("消息不能为空");
  }
  s_show.value = false;
  // 触发私有消息
  proxy.$socket.emit("private message", {
    channel: receiveId,
    msg: D.message,
    fromUser:user
  });

  let chatInfo = {
      id: receiveId,
      id2: user._id,
      avatar: "http://q4.qlogo.cn/headimg_dl?dst_uin="+sendUser.qq_account+"&spec=100",
      title: sendUser.nick_name,
      type: chatType,
      messages: [
        {
          from:"me",
          date: new Date().toLocaleTimeString(),
          msg: D.message,
          readStatus:true
        },
      ],
    };
    

    let findChatUIndex = nowChats.findIndex((v,i)=> {
        return (v.id === sendUser._id || v.id === user._id) && (v.id2 === sendUser._id || v.id2 === user._id) 
    });
    if(findChatUIndex >= 0){
      nowChats[findChatUIndex]['messages'].push({
          from:"me",
          date: new Date().toLocaleTimeString(),
          msg: D.message,
          readStatus:true
      })  
    }else{
      nowChats.push(chatInfo);
    }
    store.dispatch("notify/setNowChats",nowChats)
  const msgObj = {
    class: "me",
    content: D.message,
    // url: "http://p6.qhimg.com/bdm/384_237_0/t01f40ac9baf328486f.jpg",
  };
  if (isEmjoi.value) {
    msgObj.isEmjoi = true;
    isEmjoi.value = false;
  }
  D.msgs.push(msgObj);
  audio.value.src = sendMessage;
  audio.value.play();
  setTimeout(() => {
    audio.value.src = "";
  }, 1000);
  D.message = "";
  D.emjoi = "";
};

const playVoice = (e, msg) => {
  try {
    if (prevAudio) prevAudio.pause();
    if (prevMsg) prevMsg.isPlay = false;
    const tagName = e.target.tagName.toLowerCase();
    if (tagName === "svg") {
      e.target.nextElementSibling.play();
      msg.isPlay = true;
      prevAudio = e.target.nextElementSibling;
    }
    if (tagName === "div" && e.target.className === "mark") {
      e.target.children[1].play();
      msg.isPlay = true;
      prevAudio = e.target.children[0];
    }
    prevMsg = msg;
    setTimeout(() => {
      msg.isPlay = false;
    }, parseInt(msg.voiceDuration.substring(0, msg.voiceDuration.lastIndexOf(" "))) * 1000);
  } catch (error) {
    Toast(error.message);
  }
};

const preview = (imgsObj) => {
  const arr = [];
  for (let i = 0; i < imgsObj.length; i++) {
    if (imgsObj[i].blobSrc && imgsObj[i].isImg) {
      arr.push(imgsObj[i].blobSrc);
    }
  }
  ImagePreview(arr);
};

const addEmjoi = (emjoi) => {
  isEmjoi.value = true;
  D.message += "<img src=" + emjoi.src + " width='25' height='25' />";
  D.emjoi += emjoi.alt;
  // Toast(emjoi.src);
};
</script>

<template>
  <div class="chat" id="chat">
    <van-popup
      v-model:show="s_show"
      position="bottom"
      :style="{ height: '60%' }"
    >
      <van-search
        autofocus
        left-icon
        v-model="D.emjoi"
        show-action
        placeholder="请输入内容,回车发送..."
        @search="on_send"
      >
        <template #action>
          <div @click="on_send">发送</div>
        </template>
      </van-search>
      <div
        v-for="emm in emjoi"
        style="
          display: inline-block;
          width: 20px;
          margin: 5px;
          height: 20px;
          flex-wrap: wrap;
          height: auto;
        "
      >
        <img
          :src="emm.src"
          @click="addEmjoi(emm)"
          width="25"
          height="25"
          alt=""
        />
      </div>
    </van-popup>
    <div class="smile" @click="s_show = true">
      <van-icon name="smile" size="24px" color="#08f" />
    </div>
    <div class="voice" @click="recode_voice">
      <label>
        <input
          @change="showAudio"
          type="file"
          style="display: none"
          accept="audio/*"
          capture="microphone"
        />
        <svg
          t="1651589184251"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="2066"
          width="24"
          height="24"
        >
          <path
            d="M512 705.728c105.888 0 192-86.112 192-192L704 257.952c0-105.888-86.112-192-192-192s-192 86.112-192 192l0 255.776C320 619.584 406.112 705.728 512 705.728z"
            p-id="2067"
            fill="#0088ff"
          ></path>
          <path
            d="M864 479.776 864 352c0-17.664-14.304-32-32-32s-32 14.336-32 32l0 127.776c0 160.16-129.184 290.464-288 290.464-158.784 0-288-130.304-288-290.464L224 352c0-17.664-14.336-32-32-32s-32 14.336-32 32l0 127.776c0 184.608 140.864 336.48 320 352.832L480 896 288 896c-17.664 0-32 14.304-32 32s14.336 32 32 32l448 0c17.696 0 32-14.304 32-32s-14.304-32-32-32l-192 0 0-63.36C723.136 816.256 864 664.384 864 479.776z"
            p-id="2068"
            class="cursorsHover"
            fill="#0088ff"
          ></path>
        </svg>
      </label>
    </div>
    <div class="photo">
      <label>
        <input
          type="file"
          @change="showImg"
          style="display: none"
          accept="image/*"
        />
        <van-icon name="photo" color="#08f" size="24px" />
      </label>
    </div>
    <div class="video">
      <label>
        <input
          type="file"
          @change="showVideo"
          style="display: none"
          accept="video/*"
        />
        <van-icon name="live" color="#08f" size="24px" />
      </label>
    </div>
    <audio src="" ref="audio"></audio>
    
    <div class="other">
      <div class="avatar">
        <img
          src="https://i.picsum.photos/id/635/360/460.jpg?hmac=HB8bcPboUMPO05j4RaJRFJoIgUqF7Ec-mgCum2Yv2xE"
          alt=""
        />
      </div>
      <div class="message">
         <!-- 消息区域 -->
         <p class="m">
           你好
         </p>
      </div>
    </div>

    <div class="me" v-for="msg in D.msgs">
      <div class="avatar">
        <img
          src="https://i.picsum.photos/id/635/360/460.jpg?hmac=HB8bcPboUMPO05j4RaJRFJoIgUqF7Ec-mgCum2Yv2xE"
          alt=""
        />
      </div>
      <div class="message">
        <img
          :src="msg.blobSrc"
          @click="preview(D.msgs)"
          style="width: 80%"
          v-if="msg.isImg"
          alt=""
        />
        <video
          autoplay
          controls
          :src="msg.blobSrc"
          style="width: 80%"
          v-if="msg.isVideo"
        />
        <div
          @click="playVoice($event, msg)"
          v-if="msg.isAudio"
          class="mark"
          style="background: #08f; padding: 5px; border-radius: 5px"
        >
          <svg
            @click="playVoice($event, msg)"
            t="1651607824339"
            :class="{ icon: true, rotate: msg.isPlay }"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="2066"
            width="20"
            height="20"
          >
            <path
              d="M487.648 240a16 16 0 0 1 16-16h16a16 16 0 0 1 16 16v546.784a16 16 0 0 1-16 16h-16a16 16 0 0 1-16-16V240z m155.84 89.04a16 16 0 0 1 16-16h16a16 16 0 0 1 16 16v346.432a16 16 0 0 1-16 16h-16a16 16 0 0 1-16-16V329.04z m155.824 144.704a16 16 0 0 1 16-16h16a16 16 0 0 1 16 16v123.824a16 16 0 0 1-16 16h-16a16 16 0 0 1-16-16v-123.84z m-467.488-144.704a16 16 0 0 1 16-16h16a16 16 0 0 1 16 16v346.432a16 16 0 0 1-16 16h-16a16 16 0 0 1-16-16V329.04zM176 473.76a16 16 0 0 1 16-16h16a16 16 0 0 1 16 16v112.688a16 16 0 0 1-16 16h-16a16 16 0 0 1-16-16V473.76z"
              p-id="2067"
              class="cursorsHover"
              fill="#ffffff"
            ></path>
          </svg>
          {{ msg.voiceDuration }}
          <audio :src="msg.blobSrc"></audio>
        </div>
        <div class="m" v-if="msg.isEmjoi" v-html="msg.content"></div>
        <div
          v-if="!msg.isImg && !msg.isVideo && !msg.isAudio && !msg.isEmjoi"
          class="m"
        >
          {{ msg.content }}
        </div>
      </div>
    </div>
    <div style="height: 50px"></div>
    <van-search
      autofocus
      left-icon
      v-model="D.message"
      show-action
      class="sendMessage"
      placeholder="请输入内容,回车发送..."
      @search="on_send"
    >
      <template #action>
        <div @click="on_send">发送</div>
      </template>
    </van-search>
  </div>
</template>

<style lang="scss" scoped>
.chat {
  font: 14px/20px tahoma, arial, "Hiragino Sans GB", "\5b8b\4f53", sans-serif;
  --van-padding-sm: 5px;
  background-color: #eee;
  padding: 10px;
  .sendMessage {
    position: fixed;
    width: 100vw;
    left: 0;
    bottom: 50px;
  }
  .smile,
  .voice,
  .photo,
  .video {
    width: 40px;
    height: 40px;
    background: white;
    justify-content: center;
    position: absolute;
    left: 0;
    border-radius: 0 5px 5px 0;
    display: flex;
    align-items: center;
    z-index: 2;
    &:hover {
      opacity: 0.7;
    }
  }
  .voice {
    bottom: 120px;
  }
  .photo {
    bottom: 200px;
  }
  .video {
    bottom: 280px;
  }
  .smile {
    bottom: 360px;
  }
}

.other,
.me {
  padding: 15px 0;
  display: flex;
  .avatar {
    img {
      width: 50px;
      height: 50px;
      border-radius: 50%;
    }
    margin: 0 10px;
  }
  .message {
    width: auto;
    height: auto;
    color: white;
    text-align: right;
    .m {
      padding: 5px 10px;
      background: #08f;
      min-height: 20px;
      word-wrap: break-word;
    }
  }
}

.other {
  .avatar {
    margin-left: 0;
  }
}

.me {
  flex-direction: row-reverse;
  .avatar {
    margin-right: 0;
  }
}

.other .message .m,
.me .message .m {
  position: relative;
  border-radius: 5px;
}

.rotate {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotateX(0deg);
  }
  to {
    transform: rotateX(360deg);
  }
}
</style>
